package com.flying.refdata.service;

import com.flying.refdata.model.Quarter;
import com.flying.refdata.model.equity.EquityInfo;
import com.flying.refdata.model.equity.QuarterlyReport;
import com.flying.refdata.repository.equity.QuarterlyReportRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ReportService {
    @Autowired
    private QuarterlyReportRepository repository;
    private Map<String, QuarterlyReport> reportCache = new ConcurrentHashMap<>();

    public QuarterlyReport getQuarterlyReport(EquityInfo info, int year, Quarter quarter) {
        String key = info.getCode() + year + quarter;
        if (reportCache.containsKey(key)) return reportCache.get(key);
        QuarterlyReport report = repository.findByEquityCodeAndYearAndQuarter(info.getCode(), year, quarter);
        if (report == null) return null;
        reportCache.put(key, report);
        return report;
    }

    public QuarterlyReport getLatestQuarterlyReport(EquityInfo info, int date) {
        QuarterlyReport report = repository.findTopByEquityInfoAndDiscloseDateBeforeOrderByDiscloseDateDesc(info, date);
        if (report == null) return null;
        reportCache.put(report.getEquityInfo().getCode() + report.getYear() + report.getQuarter(), report);
        return report;
    }

    public QuarterlyReport getOrCreateQuarterlyReport(EquityInfo info, int year, Quarter quarter) {
        QuarterlyReport report = getQuarterlyReport(info, year, quarter);
        if (report == null) {
            report = new QuarterlyReport();
            report.setEquityInfo(info);
            report.setYear(year);
            report.setQuarter(quarter);
        }
        return report;
    }

    public QuarterlyReport saveQuarterlyReport(QuarterlyReport report) {
        if (report != null) {
            String key = report.getEquityInfo().getCode() + report.getYear() + report.getQuarter();
            report = repository.save(report);
            reportCache.put(key, report);
        }
        return report;
    }

    public List<QuarterlyReport> saveQuarterlyReport(Iterable<QuarterlyReport> reports) {
        List<QuarterlyReport> result = new ArrayList<>();
        if (reports == null) {
            return result;
        }
        for (QuarterlyReport report : reports) {
            result.add(saveQuarterlyReport(report));
        }
        return result;
    }
}
